package com.tchintech.pay.net;

import android.content.Context;

import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.utils.PropUtils;
import com.tchintech.pay.utils.Signature;
import com.tchintech.pay.utils.WriteLogUtil;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.params   .CoreConnectionPNames;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2017/7/6 0006.
 */

public class HttpRequester {
    public static String path(String url, Map<String, String> map) {
        String KEY = PropUtils.getProp("config").getProperty("KEY");
        String key = PropUtils.getProp("config").getProperty("key");
        String URL = PropUtils.getProp("config").getProperty("URL");
        url = URL + url;
        try {
            map.put("sign", Signature.getSign(map, KEY, key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }
    public  static void
    post(Context context, int what ,final String url, final Map<String, String> map,
                             final ResultCallback result, final File file) throws Exception {
        if (!NetUtils.isNetworkConnected(context)) {
            //无网络连接直接返回空值

            result.httpCallback("",HttpCode.networkabnormal);
            System.out.println("无网络连接");
        } else {
            System.out.println("请求参数"+map.toString());
            System.out.println("请求地址"+url);
            doPost(url, what, map, result, file);
        }
    }

    public static void doPost(final String url,final int what, final Map<String, String> map,
                              final ResultCallback result, final File file) throws Exception {
        new Thread() {
            @Override
            public void run() {
                String resultBean="";
                HttpClient httpClient = new HttpClient();
                httpClient.getParams().setContentCharset("UTF-8");
                httpClient.getParams().setSoTimeout(10000);
               httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
                PostMethod postMethod = new PostMethod(url);
                if (file != null) {
                    try {
                        List<Part> list = new ArrayList<>();
                        Set<Map.Entry<String, String>> set = map.entrySet();
                        for (Map.Entry<String, String> entry : set) {
                            list.add(new StringPart(entry.getKey(), entry
                                    .getValue()));
                        }
                        list.add(new FilePart("file", file));
                        Part[] parts = new Part[map.size() + 1];
                        list.toArray(parts);
                        postMethod.setRequestEntity(new MultipartRequestEntity(
                                parts, postMethod.getParams()));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {

                    Set<Map.Entry<String, String>> set = map.entrySet();
                    for (Map.Entry<String, String> entry : set) {
                        postMethod.addParameter(entry.getKey(),
                                entry.getValue());
                    }
                }
                try {
                    int statusCode = httpClient.executeMethod(postMethod);
                    if (statusCode != 200) {
                    } else {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        InputStream in = postMethod.getResponseBodyAsStream();
                        byte[] buf = new byte[1024];
                        int len = 0;
                        while ((len = in.read(buf)) != -1) {
                            out.write(buf, 0, len);
                        }
                        byte[] lens = out.toByteArray();
                        resultBean = URLDecoder.decode(new String(lens), "UTF-8");
                        System.out.println("post返回的数据"+resultBean);
                    }
                } catch (ConnectTimeoutException timeoutException) {
                    WriteLogUtil.i("连接超时","");
                } catch (UnknownHostException unknownHostException) {
                    WriteLogUtil.i("未知的主机","");
                } catch (ConnectException connectException) {
                    WriteLogUtil.i("链接服务器异常","");
                } catch (Exception e) {
                    WriteLogUtil.i("网络未知异常","");
                } finally {
                    WriteLogUtil.i("返回结果",resultBean);
                    result.httpCallback(resultBean, what);
                    //释放连接
                    postMethod.releaseConnection();
                }
            }
        }.start();
    }
}
